package com.lancoo.znbkxx.fragments;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lancoo.znbkxx.R;
import com.lancoo.znbkxx.adapter.SampleAdapter;
import com.lancoo.znbkxx.adapter.SearchAdapter;
import com.lancoo.znbkxx.beans.FirstPageBean;
import com.lancoo.znbkxx.beans.RevisionInfoBean;
import com.lancoo.znbkxx.beans.SampleGroupBean;
import com.lancoo.znbkxx.beans.SamplePaperBean;
import com.lancoo.znbkxx.uis.MySelectActivity;
import com.lancoo.znbkxx.views.CheckableTextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Create by TangJun on 2019/2/16
 */
public class RevisionFragment extends Fragment implements View.OnClickListener{
    private ImageView expandIcon;
    private View mPopView;
    private PopupWindow mPopupWindow;
    private PopupWindow sPopupWindow;
    private View mSearchView;
    private RecyclerView rvGroup;
    private SampleAdapter mAdapter;
    private SearchAdapter sAdapter;
    private List<SampleGroupBean> list;
    private List<SamplePaperBean> allList;
    private List<SamplePaperBean> mSearchList;
    private TextView mTotalDays;
    private TextView mFinishCount;
    private TextView mTotalCount;
    private TextView mAverage;
    private TextView mHighest;
    private TextView mLowest;
    private TextView mBai;
    private TextView mShi;
    private TextView mGe;
    private CheckableTextView m1_1;
    private CheckableTextView m1_2;
    private CheckableTextView m1_3;
    private CheckableTextView m2_1;
    private CheckableTextView m2_2;
    private CheckableTextView m2_3;
    private CheckableTextView m3_1;
    private CheckableTextView m3_2;
    private CheckableTextView m3_3;
    private CheckableTextView m3_4;
    private CheckableTextView m4_1;
    private CheckableTextView m4_2;
    private CheckableTextView m4_3;
    private CheckableTextView m4_4;
    private ImageView mReset;
    private ImageView mConfig;
    private EditText mEditText;
    private long mLastSearchTime;
    private RecyclerView rvSearch;
    private InputMethodManager mInputManager;
    private RevisionInfoBean revisionInfoBean;
    private Handler handler = new Handler();
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_revision, container, false);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initPopWindow();
        findViews(view);
        initSearchWindow();
    }

    private void  initSearchWindow(){
        mSearchView = getLayoutInflater().inflate(R.layout.view_search,null);
        sPopupWindow = new PopupWindow(mSearchView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        sPopupWindow.setOutsideTouchable(true);
    }
    private void initPopWindow() {
        mPopView = getLayoutInflater().inflate(R.layout.view_expand, null);
        // 将转换的View放置到 新建一个popuwindow对象中
        mPopupWindow = new PopupWindow(mPopView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        // 点击popuwindow外让其消失
        mPopupWindow.setOutsideTouchable(true);
        //获取焦点
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                expandIcon.setImageResource( R.mipmap.icon_expand);
            }
        });

    }

    /*@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        ((PhoneMainActivity)context).initData();
    }*/

//    public void setList(FirstPageBean bean) {
//        allList = new ArrayList<>();
//        list = new ArrayList<>();
//        List<FirstPageBean.PaperPackageListBean> paperPackageListBeans = bean.getPaperPackageList();
//        for (int i = 0; i < paperPackageListBeans.size(); i++){
//            final List<SamplePaperBean> childList = new ArrayList<>();
//            FirstPageBean.PaperPackageListBean paperPackageListBean = paperPackageListBeans.get(i);
//            List<FirstPageBean.PaperPackageListBean.PaperListBean> paperListBeans = paperPackageListBean.getPaperList();
//            if (paperListBeans.size() < 3){
//                for (int j = 0; j < paperListBeans.size(); j++){
//                    FirstPageBean.PaperPackageListBean.PaperListBean b = paperListBeans.get(j);
//                    SamplePaperBean s = new SamplePaperBean(b.getPaperID(),b.getPaperName(),b.getSubmitStuCount(),b.getTotalStuCount()
//                            ,b.getAnswerCount(),b.getTotalCount(),b.getAverageScore(),b.getHighestScore(),b.getScore(),b.getRank(),b.getStartTime()
//                            ,b.getEndTime(),b.getReleaseTime(),b.getState(),b.getLayer());
//                    childList.add(s);
//                }
//            }else {
//                for (int j = 0; j < 3; j++){
//                    FirstPageBean.PaperPackageListBean.PaperListBean b = paperListBeans.get(j);
//                    SamplePaperBean s = new SamplePaperBean(b.getPaperID(),b.getPaperName(),b.getSubmitStuCount(),b.getTotalStuCount()
//                            ,b.getAnswerCount(),b.getTotalCount(),b.getAverageScore(),b.getHighestScore(),b.getScore(),b.getRank(),b.getStartTime()
//                            ,b.getEndTime(),b.getReleaseTime(),b.getState(),b.getLayer());
//                    childList.add(s);
//                }
//            }
//            for (int k = 0; k < paperListBeans.size(); k++){
//                FirstPageBean.PaperPackageListBean.PaperListBean b = paperListBeans.get(k);
//                SamplePaperBean s = new SamplePaperBean(b.getPaperID(),b.getPaperName(),b.getSubmitStuCount(),b.getTotalStuCount()
//                        ,b.getAnswerCount(),b.getTotalCount(),b.getAverageScore(),b.getHighestScore(),b.getScore(),b.getRank(),b.getStartTime()
//                        ,b.getEndTime(),b.getReleaseTime(),b.getState(),b.getLayer());
//                allList.add(s);
//            }
//            SamplePaperBean foot = new SamplePaperBean("f","f",0,0,0,0
//                    ,0,0,0,0,"","","",5,0);
//            childList.add(foot);
//            list.add(new SampleGroupBean(childList,paperPackageListBean.getPackageName(),paperPackageListBean.getFinshCount()+""
//                    ,paperPackageListBean.getTotalCount()+"",paperPackageListBean.getEndTime(),childList.get(0).getLayer()));
//
//        }
//        rvGroup.setLayoutManager(new LinearLayoutManager(getActivity()));
//        mAdapter = new SampleAdapter(list,getActivity());
//        rvGroup.setAdapter(mAdapter);
//
//    }
    public void setText(FirstPageBean bean){
        mTotalDays.setText(bean.getTotalDays()+"");
        mFinishCount.setText(bean.getFinishCount()+"");
        mTotalCount.setText("/"+bean.getTotalCount()+"");
        mAverage.setText(Math.round(bean.getAverageScore())+"");
        mHighest.setText(Math.round(bean.getHighestScore())+"");
        mLowest.setText(Math.round(bean.getLowestScore())+"");
        String num = bean.getLeftDays()+"";
        if (bean.getLeftDays() > 99){
            mBai.setText(num.charAt(0)+"");
            mShi.setText(num.charAt(1)+"");
            mGe.setText(num.charAt(2)+"");
        }else if (bean.getLeftDays() > 9 && bean.getLeftDays() < 100){
            mBai.setVisibility(View.INVISIBLE);
            mShi.setText(num.charAt(0)+"");
            mGe.setText(num.charAt(1)+"");
        }else {
            mBai.setVisibility(View.INVISIBLE);
            mShi.setVisibility(View.INVISIBLE);
            mGe.setText(num.charAt(0)+"");
        }
    }
    private void findViews(final View view) {
        /*((PhoneMainActivity)getActivity()).initData();*/
        //list = new ArrayList<>();
        expandIcon = view.findViewById(R.id.expandIcon);
        rvGroup = view.findViewById(R.id.rv_group);
        mTotalDays = view.findViewById(R.id.tv_total_day);
        mFinishCount = view.findViewById(R.id.tv_finish_count);
        mTotalCount = view.findViewById(R.id.tv_total_count);
        mAverage = view.findViewById(R.id.tv_average);
        mHighest = view.findViewById(R.id.tv_highest);
        mLowest = view.findViewById(R.id.tv_lowest);
        mBai = view.findViewById(R.id.tv_bai);
        mShi = view.findViewById(R.id.tv_shi);
        mGe = view.findViewById(R.id.tv_ge);
        m1_1 = mPopView.findViewById(R.id.tv_1_1);
        m1_2 = mPopView.findViewById(R.id.tv_1_2);
        m1_3 = mPopView.findViewById(R.id.tv_1_3);
        m2_1 = mPopView.findViewById(R.id.tv_2_1);
        m2_2 = mPopView.findViewById(R.id.tv_2_2);
        m2_3 = mPopView.findViewById(R.id.tv_2_3);
        m3_1 = mPopView.findViewById(R.id.tv_3_1);
        m3_2 = mPopView.findViewById(R.id.tv_3_2);
        m3_3 = mPopView.findViewById(R.id.tv_3_3);
        m3_4 = mPopView.findViewById(R.id.tv_3_4);
        m4_1 = mPopView.findViewById(R.id.tv_4_1);
        m4_2 = mPopView.findViewById(R.id.tv_4_2);
        m4_3 = mPopView.findViewById(R.id.tv_4_3);
        m4_4 = mPopView.findViewById(R.id.tv_4_4);
        mReset = mPopView.findViewById(R.id.iv_reset);
        mConfig = mPopView.findViewById(R.id.iv_config);
        mEditText = view.findViewById(R.id.etSearch);
        m1_1.setOnClickListener(this);
        m1_2.setOnClickListener(this);
        m1_3.setOnClickListener(this);
        m2_1.setOnClickListener(this);
        m2_2.setOnClickListener(this);
        m2_3.setOnClickListener(this);
        m3_1.setOnClickListener(this);
        m3_2.setOnClickListener(this);
        m3_3.setOnClickListener(this);
        m3_4.setOnClickListener(this);
        m4_1.setOnClickListener(this);
        m4_2.setOnClickListener(this);
        m4_3.setOnClickListener(this);
        m4_4.setOnClickListener(this);
        mReset.setOnClickListener(this);
        mConfig.setOnClickListener(this);
        expandIcon.setOnClickListener(this);
        expandIcon.setImageResource(mPopupWindow.isShowing()? R.mipmap.icon_expand_e : R.mipmap.icon_expand);
        mEditText.setOnEditorActionListener(new EditEditorActionListener());
        mEditText.addTextChangedListener(new EditTextChangeListener());
    }

    private void getDate() {
        list = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            final List<SamplePaperBean> childList = new ArrayList<>(i);
          /*  SamplePaperBean s1 = new SamplePaperBean("10","试卷1",20,50,0,5
            ,90,75,0,10,"111","121","131",true);
            SamplePaperBean s2 = new SamplePaperBean("11","试卷2",20,50,2,5
                    ,90,75,0,10,"111","121","131",false);
            SamplePaperBean s3 = new SamplePaperBean("10","试卷3",20,50,5,5
                    ,90,75,80,10,"111","121","131",false);
            childList.add(s1);*/
          /*  childList.add(s2);
            childList.add(s3);*/
            // list.add(new SampleGroupBean(childList, "基础复习试卷包 " + i,"20","50","2018"));
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.expandIcon :
                showPopWindow();
                break;
            case R.id.tv_1_1:
                m1_1.setChecked(m1_1.isChecked() ? false : true);
                m1_1.setTextColor(m1_1.isChecked() ? Color.parseColor("#ff5000") : Color.parseColor("#353535"));
                break;
            case R.id.tv_1_2:
                m1_2.setChecked(m1_2.isChecked() ? false : true);
                m1_2.setTextColor(m1_2.isChecked() ? Color.parseColor("#ff5000") : Color.parseColor("#353535"));
                break;
            case R.id.tv_1_3:
                m1_3.setChecked(m1_3.isChecked() ? false : true);
                m1_3.setTextColor(m1_3.isChecked() ? Color.parseColor("#ff5000") : Color.parseColor("#353535"));
                break;
            case R.id.tv_2_1:
                m2_1.setChecked(m2_1.isChecked() ? false : true);
                m2_1.setTextColor(m2_1.isChecked() ? Color.parseColor("#ff5000") : Color.parseColor("#353535"));
                break;
            case R.id.tv_2_2:
                m2_2.setChecked(m2_2.isChecked() ? false : true);
                m2_2.setTextColor(m2_2.isChecked() ? Color.parseColor("#ff5000") : Color.parseColor("#353535"));
                break;
            case R.id.tv_2_3:
                m2_3.setChecked(m2_3.isChecked() ? false : true);
                m2_3.setTextColor(m2_3.isChecked() ? Color.parseColor("#ff5000") : Color.parseColor("#353535"));
                break;
            case R.id.tv_3_1:
                m3_1.setChecked(m3_1.isChecked() ? false : true);
                m3_1.setTextColor(m3_1.isChecked() ? Color.parseColor("#ff5000") : Color.parseColor("#353535"));
                break;
            case R.id.tv_3_2:
                m3_2.setChecked(m3_2.isChecked() ? false : true);
                m3_2.setTextColor(m3_2.isChecked() ? Color.parseColor("#ff5000") : Color.parseColor("#353535"));
                break;
            case R.id.tv_3_3:
                m3_3.setChecked(m3_3.isChecked() ? false : true);
                m3_3.setTextColor(m3_3.isChecked() ? Color.parseColor("#ff5000") : Color.parseColor("#353535"));
                break;
            case R.id.tv_3_4:
                m3_4.setChecked(m3_4.isChecked() ? false : true);
                m3_4.setTextColor(m3_4.isChecked() ? Color.parseColor("#ff5000") : Color.parseColor("#353535"));
                break;
            case R.id.tv_4_1:
                m4_1.setChecked(m4_1.isChecked() ? false : true);
                m4_1.setTextColor(m4_1.isChecked() ? Color.parseColor("#ff5000") : Color.parseColor("#353535"));
                break;
            case R.id.tv_4_2:
                m4_2.setChecked(m4_2.isChecked() ? false : true);
                m4_2.setTextColor(m4_2.isChecked() ? Color.parseColor("#ff5000") : Color.parseColor("#353535"));
                break;
            case R.id.tv_4_3:
                m4_3.setChecked(m4_3.isChecked() ? false : true);
                m4_3.setTextColor(m4_3.isChecked() ? Color.parseColor("#ff5000") : Color.parseColor("#353535"));
                break;
            case R.id.tv_4_4:
                m4_4.setChecked(m4_4.isChecked() ? false : true);
                m4_4.setTextColor(m4_4.isChecked() ? Color.parseColor("#ff5000") : Color.parseColor("#353535"));
                break;
            case R.id.iv_reset:
                m1_1.setChecked(false);
                m1_2.setChecked(false);
                m1_3.setChecked(false);
                m2_1.setChecked(false);
                m2_2.setChecked(false);
                m2_3.setChecked(false);
                m3_1.setChecked(false);
                m3_2.setChecked(false);
                m3_3.setChecked(false);
                m4_1.setChecked(false);
                m4_2.setChecked(false);
                m4_3.setChecked(false);
                m4_4.setChecked(false);
                m3_4.setChecked(false);
                m1_1.setTextColor(Color.parseColor("#353535"));
                m1_2.setTextColor(Color.parseColor("#353535"));
                m1_3.setTextColor(Color.parseColor("#353535"));
                m2_1.setTextColor(Color.parseColor("#353535"));
                m2_2.setTextColor(Color.parseColor("#353535"));
                m2_3.setTextColor(Color.parseColor("#353535"));
                m3_1.setTextColor(Color.parseColor("#353535"));
                m3_2.setTextColor(Color.parseColor("#353535"));
                m3_3.setTextColor(Color.parseColor("#353535"));
                m4_1.setTextColor(Color.parseColor("#353535"));
                m4_2.setTextColor(Color.parseColor("#353535"));
                m4_3.setTextColor(Color.parseColor("#353535"));
                m3_4.setTextColor(Color.parseColor("#353535"));
                m4_4.setTextColor(Color.parseColor("#353535"));
                break;
            case R.id.iv_config:
                startActivity(new Intent(getActivity(), MySelectActivity.class));
                break;

        }
    }

    private void showPopWindow() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        } else {
            mPopupWindow.showAsDropDown(expandIcon, 0, 0);
            expandIcon.setImageResource( R.mipmap.icon_expand_e);
        }
    }
    private void showSPopWindow() {
        if (sPopupWindow != null && sPopupWindow.isShowing()) {
            sPopupWindow.dismiss();
        } else {
            sPopupWindow.showAsDropDown(expandIcon, 0, 0);
            //expandIcon.setImageResource( R.mipmap.icon_expand_e);
        }
    }
    protected class EditEditorActionListener implements TextView.OnEditorActionListener {

        @Override
        public boolean onEditorAction(TextView textView, int actionId,
                                      KeyEvent keyEvent) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                searchPaperByKeyword();
            }
            return true;
        }
    }

    private void searchPaperByKeyword() {
        mSearchList = new ArrayList<>();
        String trim = mEditText.getText().toString().trim();
        if (System.currentTimeMillis() - mLastSearchTime > 1000) {
            mLastSearchTime = System.currentTimeMillis();
        } else {
            return;
        }
        if (!TextUtils.isEmpty(trim)) {
            //showProcessDialog(this);
            showSPopWindow();
            LinearLayoutManager manager = new LinearLayoutManager(getActivity());
            rvSearch = mSearchView.findViewById(R.id.rv_search);
            sAdapter = new SearchAdapter(getActivity(),mSearchList);
            rvSearch.setItemAnimator(new DefaultItemAnimator());
            rvSearch.setLayoutManager(manager);
            rvSearch.setAdapter(sAdapter);
            searchPaperData(trim);
        }
        hideKeyboard();
    }
    private void searchPaperData(String keyString) {
        mSearchList.clear();
        sAdapter.setKeyString(keyString);
        for (int i = 0; i < allList.size(); i++) {
            if (null != allList.get(i).getPaperName() && allList.get(i)
                    .getPaperName().toLowerCase().contains(keyString.toLowerCase())) {
                mSearchList.add(allList.get(i));
            }
        }
        //dismissProcessDialog();
        if (mSearchList.size() > 0) {
            sAdapter.notifyDataSetChanged();
        }
    }

    public void hideKeyboard() {
        if (mInputManager == null) {
            mInputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        }
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams
                .SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null) {
                mInputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
    private class EditTextChangeListener implements TextWatcher {

        @Override
        public void afterTextChanged(Editable s) {
            String s1 = s + "";
            //mNodataLayout.setVisibility(View.GONE);
            if (s1.length() > 0) {
            } else {
            }
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {

        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                  int arg3) {
            if (TextUtils.isEmpty(arg0.toString())) {
            } else {
            }
        }
    }
}


